//
//  UserAccount.swift
//  LEOweibo
//
//  Created by zz on 16/3/6.
//  Copyright © 2016年 zz. All rights reserved.
//

import UIKit

class UserAccount: NSObject {
    
    //MARK:- 单例
    static let sharedUserAccount = UserAccount()
    
    //MARK:- 属性
    
    var isLogin: Bool{
        
        return access_token != nil
    }
    //当前授权用户的uid
    var uid: String?
    
    var access_token: String?
    
    var expiresDate: NSDate?
    //过期时间
    var expires_in: NSTimeInterval = 0{
        didSet{
            expiresDate = NSDate(timeIntervalSinceNow: self.expires_in)
        }
    }
    //用户头像
    var avatar_large: String?
    //用户昵称
    var screen_name: String?
    
    
    //MARK:- 构造函数
    private override init() {
        
        super.init()
        loadData()
    }
    init(dict:[String:AnyObject]) {
        
        super.init()
        
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String){}
    
    //    MARK:- description
    override var description: String{
        let dict = ["access_token", "uid", "screen_name", "avatar_large", "expiresDate"]
        return dictionaryWithValuesForKeys(dict).description
        
    }
}

//MARK:- 加载和保存用户数据
extension UserAccount {
    ///更新数据
    func updateDate(dict:[String:AnyObject]) {
        setValuesForKeysWithDictionary(dict)
        saveData()
    }
    ///加载数据
    private func loadData() {
        guard let dict =  NSUserDefaults.standardUserDefaults().objectForKey(LeoUserInfoKey) as! [String:AnyObject]? else{
            print("用户信息读取有误")
            return
        }
        setValuesForKeysWithDictionary(dict)
        if isExpired() {
            print("过期了")
            access_token = nil
        }else{
            print("没有过期")
        }
        
    }
    ///保存数据
    private func saveData() {
        
        let keys = ["access_token", "uid", "screen_name", "avatar_large", "expiresDate"]
        let dict = dictionaryWithValuesForKeys(keys)
        NSUserDefaults.standardUserDefaults().setObject(dict, forKey: LeoUserInfoKey)
    }
    
    ///判断是否过期
    private func isExpired()->Bool {
        let result = expiresDate!.compare(NSDate())
        return result == .OrderedAscending ? true : false
    }
}
